<?php
namespace App\Repositories;

use App\Models\GameServer\UserInfo;
use App\Models\GameServer\OnlineUser;
use Illuminate\Support\Facades\Cache;
use Illuminate\Pagination\LengthAwarePaginator;
use Carbon\Carbon;
use Redis,DB;

use App\Models\GameServer\PlayRecord;

/**
* df
*/
class GamerRepository
{
    protected $Redis;

    public function __construct()
    {
        $this->Redis = Redis::connection();

    }

    //获取所有玩家 -- Redis方式
    public function getGamers111($request)
    {
        $gamers = [];

        //玩家账户列表
        $gamer_accounts = $this->Redis->zrange('zset_user_abiliy_score', 0, -1);

        foreach ($gamer_accounts as $gamer) {
            $gamers[] = $this->Redis->hgetall($gamer);
        }

        $gamers = collect($gamers);//结果集
        $total = $gamers->count();//总记录数
        $perPage = 10;//每页个数

        if ($request->has('page')) {
            $currentPage = (int)$request->page > 0 ?  $request->page : 1;
        } else {
            $currentPage = 1; //当前页
        }

        $gamers = $gamers->slice(($currentPage - 1) * $perPage, $perPage);

        $path = LengthAwarePaginator::resolveCurrentPath();
        $options = ['path' => $path];

        //手动切割传递给分页器的结果集只取10个
        $gamers = new LengthAwarePaginator($gamers, $total, $perPage, $currentPage, $options);

        return $gamers;
    }

    //获取所有玩家--mysql
    public function getGamers($request)
    {
        $params = $request->all();

        $keywords = empty($params['search']['value']) ? '': $params['search']['value'];
        $offset = $params['start'];
        $limit = $params['length'];

        $total = UserInfo::when($keywords, function($query) use ($keywords) {
            return $query->where('id', $keywords)->orWhere('nickname', '%'.$keywords.'%');
        })->count();

        $gamers = UserInfo::when($keywords, function($query) use ($keywords, $offset, $limit) {
            return $query->where('id', $keywords)->orWhere('nickname','like', '%'.$keywords.'%');
        })->offset($offset)->limit($limit)->orderBy('id','desc')->get();

        $res = [];
        $res['draw'] = $params['draw'];
        $res['recordsTotal'] = $total;
        $res['recordsFiltered'] = $total;
        $res['data'] = $gamers ? $gamers : [];

        return $res;
    }


    //获取所有玩家
    public function getGamers1111()
    {
        $gamers = UserInfo::all();
        // dd($gamers);
        return $gamers;

    }

    //在线玩家
    public function getOnlineGamers()
    {
        $gamers = OnlineUser::with('userInfo')->get();

        return $gamers;
    }

    //获取黑名单玩家
    public function getBlackListGamers()
    {
        $gamers = UserInfo::where('status', 3)->get();

        return $gamers;
    }

    //获取禁言玩家
    public function getforbiddenGamers()
    {
        $gamers = UserInfo::where('status', 2)->get();

        return $gamers;
    }

    //获取指定玩家信息
    public function getGamer($id)
    {
        $gamer = UserInfo::find($id);
        return $gamer;
    }

    //加入黑名单
    public function pushBlackList($request, $id)
    {
        $gamer = UserInfo::findOrFail($id);

        $gamer->status = 3;
        $gamer->freeze_reason = $request->desc;
        $gamer->save();

        $this->Redis->hset($gamer->account_name, 'status', 3);
        $this->Redis->hset($gamer->account_name, 'freeze_reason', $request->desc);

        return true;
    }

    //移出黑名单
    public function popBlackList($id)
    {
        $gamer = UserInfo::findOrFail($id);

        $gamer->status = 1;
        $gamer->freeze_reason = '';
        $gamer->save();

        $this->Redis->hset($gamer->account_name, 'status', 1);
        $this->Redis->hset($gamer->account_name, 'freeze_reason', '');

        return true;
    }

    //删除玩家
    public function destroyGamer($id)
    {
        $gamer = UserInfo::findOrFail($id);
        $gamer->delete();

        $this->Redis->del($gamer->account_name);

        return true;
    }

    //批量删除
    public function destroyList($ids)
    {
        for ($i = 0; $i < count($ids); $i++) {
            $this->destroyGamer($ids[$i]);
        }

        return true;
    }

    /**
     * 部分更新
     * @param  [type] $id     [description]
     * @param  array  $params [description]
     * @return [type]         [description]
     */
    public function patchGamer($id, array $params)
    {
        return UserInfo::where('id', $id)->update($params);
    }

    //统计用户总数
    public static function getGamerNum()
    {
        return UserInfo::count();
    }

    //分时间段获取新增用户
    public static function getRegGamerBytime($where)
    {
        // $start = Carbon::createFromTimestamp(1510044002);

        $today_reg_gamers = UserInfo::select(DB::raw('FROM_UNIXTIME(reg_time, "'.$where['format'].'") as time'), DB::raw('COUNT(*) as num'))
                                    ->whereBetween('reg_time', [$where['start'], $where['end']])
                                    ->groupBy('time')
                                    ->get();
                                    // ->toArray();
        // dd($today_reg_gamers);
        return $today_reg_gamers;
    }


    public function getDateFromRange($startdate, $enddate){

        $startdate = strtotime($startdate);
        $enddate = strtotime($enddate);
        while($startdate <= $enddate){
            $datearr[] = date('Y-m-d',$startdate);//得到dataarr的日期数组。
            $startdate = $startdate + 3600*24;
        }
        return $datearr;
    }

    //获取新增用户数 -- 根据时间段
    public static function getNewGamerNum($where)
    {
        $num = UserInfo::where('distributer_id', $where['channel'])
                        ->whereBetween('reg_time', [$where['start'], $where['end']])
                        ->groupBy('distributer_id')
                        ->count();
        return $num;
    }

    //获取新增用户 -- 日期渠道分组
    public static function getNewGamerOfChannel($where)
    {
        $channel = $where['channel'];

        $gamers = UserInfo::select('distributer_id', DB::raw('FROM_UNIXTIME(reg_time, "%Y-%m-%d") as date,count(*) as count'))
                        ->when($channel, function ($query) use ($channel) {
                            return $query->whereIn('distributer_id', $channel);
                        })
                        ->whereBetween('reg_time', [$where['start'], $where['end']])
                        ->groupBy('distributer_id', 'date')
                        ->orderBy('date', 'asc')
                        ->get();
        return $gamers;
    }

    //获取活跃用户数,根据最近登录时间统计
    public static function getActiveGamerNum($where)
    {
        $num = UserInfo::where('distributer_id', $where['channel'])
                            ->whereBetween('login_time_lately', [$where['start'], $where['end']])
                            ->groupBy('distributer_id')
                            ->count();
        return $num;
    }

    //获取有效用户--渠道
    public static function getValidActiveGamerNum($where)
    {
        $res = UserInfo::select('distributer_id', DB::raw('count(*) as count'))
                        ->whereIn('id', $where['ids'])
                        ->groupBy('distributer_id')
                        ->get();
        return $res;
    }

    //获取某一天新增用户
    public function getNewGamer($where = null)
    {
        $gamers = UserInfo::where('distributer_id', $where['channel'])
                            ->whereBetween('reg_time', [$where['start'], $where['end']])
                            ->get();

        return $gamers;
    }
}